/**
 * Controller for the application. Orchestrates the other classes;
 * handles loads/unloads controls
 */
jsx3.lang.Package.definePackage(
    "snowsoft.gibay",
    function(gibay){
	
	//private method for preload 
	 var _preload = function(){
		
		gibay.publish({subject:gibay.Event.ON_APPLOAD,target:gibay});

		//change category list to default category "AllCategories"	
		var docNav = gibay.ModelManager.getNavPath();
		var cateID = docNav.selectNodes("//record").getItem(0).getAttribute("jsxid");
		var cateName = docNav.selectNodes("//record").getItem(0).getAttribute("Name");
		var cateLevel = docNav.selectNodes("//record").getItem(0).getAttribute("CategoryLevel");
		gibay.changeCategory(cateID,cateName,parseInt(cateLevel),null);	

		//render tabs for customize my own style
		gibay.APP.getJSXByName("tabHome").setText("<img src='"+gibay.APP.resolveURI("images/home.png")+"' height=22 width=22 /><span>Home</span>",true); 	
		gibay.APP.getJSXByName("tabFind").setText("<img src='"+gibay.APP.resolveURI("images/find.png")+"' height=22 width=22 /><span>Find</span>",true); 	
		gibay.APP.getJSXByName("tabMyItems").setText("<img src='"+gibay.APP.resolveURI("images/myitems.png")+"' height=22 width=22 /><span>My Items</span>",true); 	

		//fix tab init select state bug
		snowsoft.gibay.publish({subject:snowsoft.gibay.Event.ON_REFRESHHOME,target:this});
				
	 };
	
	 //private method for update category navigation bar.this method will move to Home.js when I reconstruct the architecture
	 var _updateCategoryNavbar = function(){
		var navbar = gibay.APP.getJSXByName("navbar_category");
		var objDoc = gibay.ModelManager.getNavPath();
		var objRecs = objDoc.selectNodes("//record");
		var html = "";
    		for(var i=0;i<objRecs.getLength();i++) {
      			var objRec = objRecs.getItem(i);
			html += '<a class="funclink" href="javascript:{void(0);}" onclick="snowsoft.gibay.changeCategory('+objRec.getAttribute("jsxid")+',\''+objRec.getAttribute("jsxtest")+'\','+parseInt(objRec.getAttribute("CategoryLevel"))+',this);return false;">'+objRec.getAttribute("Name")+'</a>';
			if(i!=objRecs.getLength()-1)
				html += '&nbsp;&gt;&nbsp;';

      		}

		navbar.setText(html,true);

	 };

	//method for initialization
   	 gibay.initialize = function(){
		
	 	var Logger = jsx3.util.Logger;
		gibay._LOG = Logger.getLogger("snowsoft.gibay");
		gibay._LOG.info("app initialized");

		//preLoad the script files asynchronously
		var sFiles = ["Home.js","Find.js","MyItems.js","ViewItemDetail.js","ModelManager.js"];
		for(var i=0;i<sFiles.length;i++)
			gibay.APP.loadInclude(gibay.APP.resolveURI("js/snowsoft/gibay/" + sFiles[i]),sFiles[i],"script",false);
		

		setTimeout(_preload,100);			
	 };

	//method for Ensures the proper handler class is loaded before routing the event to the application server 
	 gibay.publish = function(objEvent){
		switch(objEvent.subject){
			case gibay.Event.ON_APPLOAD:
				jsx3.require('snowsoft.gibay.ModelManager');
				gibay.APP.publish(objEvent);
				break;
			case gibay.Event.ON_MODELPOPULARKEYWORDSUPDATED:
			case gibay.Event.ON_REFRESHHOME:
				jsx3.require('snowsoft.gibay.Home');
				gibay.APP.getJSXByName("tabHome").doShow();
				gibay.APP.publish(objEvent);
				break;
			case gibay.Event.ON_CATEGORY_CHANGES:
				jsx3.require("snowsoft.gibay.Home");
				_updateCategoryNavbar();
				gibay.APP.publish(objEvent);
				break;
			case gibay.Event.ON_SEARCH:
				jsx3.require("snowsoft.gibay.Find");
				gibay.APP.getJSXByName("tabFind").doShow();
				if(!gibay.APP.getJSXByName("mtxItems")){
					gibay.APP.getJSXByName("paneFind").loadAndCache("components/resultContainer.xml",true);	

				}
				gibay.APP.publish(objEvent);		
				break;
			case gibay.Event.ON_VIEWITEM:
				jsx3.require("snowsoft.gibay.Find");
				gibay.APP.publish(objEvent);
				break;
			case gibay.Event.ON_CATEGORYLISTING:
				jsx3.require("snowsoft.gibay.Find");
				gibay.APP.getJSXByName("tabFind").doShow();
				if(!gibay.APP.getJSXByName("mtxItems")){
					gibay.APP.getJSXByName("paneFind").loadAndCache("components/resultContainer.xml",true);	
				}
				gibay.APP.publish(objEvent);
				break;
			case gibay.Event.ON_VIEWMYITEMS:
				jsx3.require("snowsoft.gibay.MyItems");
				gibay.APP.getJSXByName("tabMyItems").doShow();
				if(!gibay.APP.getJSXByName("blkMyItems")){
					gibay.APP.getJSXByName("paneMyItems").loadAndCache("components/myItemContainer.xml",true);	
					 
				}
				gibay.APP.publish(objEvent);
				break;
			default :
				gibay.APP.publish(objEvent);
				break;
		}
	 };
	
	 //method for user doubule click the category to show next level category
	 gibay.changeCategory = function(cateID,cateName,cateLevel,srcElement){
		var doc = gibay.ModelManager.getNavPath();
		if(doc == null){
			gibay._LOG.error("System didn't initialized category navigation path document successfully");	
		}
		var objRecs = doc.selectNodes("//record");
		var delFlag = false;
    		for(var i=0;i<objRecs.getLength();i++) {
      			var objRec = objRecs.getItem(i);
			if(delFlag == true){
				doc.deleteRecord(objRec.getAttribute("jsxid"));	
				continue;
			}else if(parseInt(objRec.getAttribute("jsxid"))==cateID){
				delFlag = true;
			}
			
      		}
		if(delFlag == false){
			var rec = {jsxid:cateID,jsxtext:cateName,Name:cateName,CategoryLevel:cateLevel};
			doc.insertRecord(rec);
		}

		gibay.publish({subject:gibay.Event.ON_CATEGORY_CHANGES,target:gibay,categoryID:cateID,categoryName:cateName,categoryLevel:parseInt(cateLevel)});

	 };
	
	
	//method for add categories to search list
	gibay.addCategoryToSearchList = function(categoryID){
		gibay._LOG.info("Add a category ID:"+categoryID+" into my categories list");
		var recID = categoryID;	
		var objMtxCategories = gibay.APP.getJSXByName("mtxCategories");
		var objBlkSearchList = gibay.APP.getJSXByName("blkSearchList");
		var objRecord = objMtxCategories.getRecord(recID);

		//my categories list don't allow dupes
		if(objRecord.jsxunselectable != "1"){
			var category = objBlkSearchList.loadAndCache("components/cmpCategory2Search.xml",false);	
			category.getDescendantOfName("lblCategoryName").setText(objRecord.CategoryName).setTip("Category:"+objRecord.jsxtext);
			category.setName("category"+objRecord.jsxid);
			category.persistent = false;
			category.recordProperties = objRecord;
			//update view
			objBlkSearchList.paintChild(category);

			//TO DO: disable the row, since it can't be added a second time?
    		objMtxCategories.insertRecordProperty(recID,"jsxunselectable","1",false);
    		objMtxCategories.insertRecordProperty(recID,"jsxcellstyle","color:#e6e6e6;",true);
			objMtxCategories.repaintData();
			gibay.publish({subject:gibay.Event.ON_CATEGORYLISTING,target:gibay,categoryData:objRecord});
		}
		
	};
	//method for remove category from my category list	
	gibay.removeCategory = function(btnRemove){
		var record = btnRemove.getParent().recordProperties;
		var category = btnRemove.getParent();
		var objBlkSearchList = category.getParent();
		objBlkSearchList.removeChild(category);
		
    	//re-enable the row in the category matrix 
		var objMtxCategories = gibay.APP.getJSXByName("mtxCategories");
		objMtxCategories.deleteRecordProperty(record.jsxid,"jsxunselectable",false);
    		objMtxCategories.deleteRecordProperty(record.jsxid,"jsxcellstyle",true);
		objMtxCategories.repaintData();
    
	};

});

/**
 * Static class maintains no global or instance variables
 * Defination of all events of application 
 * Used as a enumration 
 * @author digitalghost.liu@gmail.com 
 */
jsx3.lang.Class.defineClass("snowsoft.gibay.Event",null,[],function(Event){
	Event.ON_APPLOAD = "application is onloaded";
	Event.ON_REFRESHHOME = "when infomation changes,the app needs to refresh home tab view";
	Event.ON_CATEGORY_CHANGES = "on user change categories";
	Event.ON_SEARCH = "on user click search button or change to find tab";		
	Event.ON_SORTTYPE_CHANGES = "on user change the sort type of item result list";		
	Event.ON_VIEWITEM = "on user click item to view item detail";		
	Event.ON_CATEGORYLISTING = "on user click list category button to list items in specified category";		
	Event.ON_PRICEFILTER_CHANGES = "on user change the price filter for search item results";		
	Event.ON_VIEWSTYLE_CHANGES = "on user change the slider to redefine the item list view style";		
	Event.ON_VIEWMYITEMS = "on user change to MyItems tab";		
	Event.ON_VIEWMYITEMS_CHANGEMODEL = "on user change the view model of my items,for exp:recent items or wathlist";		
	//Model updated events
	Event.ON_MODELPOPULARKEYWORDSUPDATED = "on popular keywords cdf document updated";

});


